<template>
    <div>
      <div class="tool-box">
        <el-button size="mini" :type="isDrawing ? 'warning' : 'primary'" @click="startDraw">绘制区域</el-button>
   
        <el-button size="mini"  type="danger" :disabled="isDrawing" @click="clearAll">全部清除</el-button>
        <el-button size="mini"  type="success" :disabled="isDrawing" @click="savePoints">保存</el-button>
      </div>
      <div class="canvas-wrap">
        <canvas id="imgCanvas" ref="canvaxbox"></canvas>
        <!--用来和鼠标进行交互操作的canvas-->
        <canvas id="drawCanvas" ref="canvas" :style="{cursor: isDrawing?'crosshair': 'default'}"> </canvas>
        <!--存储已生成的点线，避免被清空-->
        <canvas id="saveCanvas" ref="canvasSave"></canvas>
      </div>
    </div>
    
  </template>
  <script>
  // import OldJs from './oldJs.js'
  export default {
    // mixins: [OldJs],
    data() {
      return {
        imgUrl: 'img/code/wechat-code.jpg',
        isDrawing: false, // 是否正在绘制
        ratio: 1,
        imgWidth: 3020,
        imgHeight: 1080,
        wrapWidth: 300,
        wrapHeight: 300,
        canvasWidth: 300,
        canvasHeight: 300,
        drawingPoints: [],
        drawedPoints: [],
        imgCanvas: null,
        imgCtx: null,
        drawCanvas: null,
        drawCtx: null,
        saveCanvas: null,
        saveCtx: null,
        submitData: [
          "1150,38,1040,167",
          "12,694,348,167"
        ]
      }
    },
    mounted() {
      this.initCanvas()
      this.getImage()
    },
    methods: {
      initCanvas() { // 初始化canvas画布
   
        let canvasWrap = document.getElementsByClassName('canvas-wrap')
        this.wrapWidth = canvasWrap [0].clientWidth
        this.wrapHeight = canvasWrap [0].clientHeight
   
        this.imgCanvas = document.getElementById('imgCanvas')
        this.imgCtx = imgCanvas.getContext('2d')
   
        // 绘制canvas
        this.drawCanvas = document.getElementById('drawCanvas')
        this.drawCtx = drawCanvas.getContext('2d')
   
        // 保存绘制区域 saveCanvas
        this.saveCanvas = document.getElementById('saveCanvas')
        this.saveCtx = saveCanvas.getContext('2d')
        // this.initImgCanvas()
      },
      initImgCanvas() {
        // 计算宽高比
        let ww = this.wrapWidth // 画布宽度
        let wh = this.wrapHeight // 画布高度
        let iw = this.imgWidth // 图片宽度
        let ih = this.imgHeight // 图片高度

        // 图片加载绘制
        let img = new Image()
        // let img = document.createElement('img')
        img.src =  this.imgUrl
   
        img.onload = () => {
            console.log('图片已加载')
            this.canvasWidth = img.width // 图片宽度
            this.canvasHeight = img.height // 图片高度

            // 初始化画布大小
            imgCanvas.width = this.canvasWidth
            imgCanvas.height = this.canvasHeight
            drawCanvas.width = this.canvasWidth
            drawCanvas.height = this.canvasHeight
            saveCanvas.width = this.canvasWidth
            saveCanvas.height = this.canvasHeight
            this.imgCtx.drawImage(img, 0, 0, this.canvasWidth, this.canvasHeight)
            this.renderDatas() // 渲染原有数据
        }
      },
      startDraw() { // 绘制区域
        if (this.isDrawing) {
            return
        }
        this.isDrawing = true
        // 绘制逻辑
        drawCanvas.addEventListener("click", this.drawImageClickFn)
        // drawCanvas.addEventListener("dblclick", this.drawImageDblClickFn)
        drawCanvas.addEventListener("mousemove", this.drawImageMoveFn)
      },
      clearAll() { // 清空所有绘制区域
        this.saveCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
        this.drawedPoints = []
      },
      getImage() { // 请求图片
        
        setTimeout(() => {
            this.imgUrl = 'https://ts1.cn.mm.bing.net/th/id/R-C.774b9223b5a3526c61691fcc5ecb3145?rik=i7Rvf49CF7Zc4w&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50041%2f7432.jpg_wh1200.jpg&ehk=969PSODhgWgR359dXTJbOB4maXRx3XZ536jGL%2fUyUy0%3d&risl=&pid=ImgRaw&r=0'
            // this.imgWidth = 500
            // this.imgHeight = 500
            this.imgUrl && this.initImgCanvas()
        }, 500)
      },
      drawImageClickFn(e) {
        let drawCtx = this.drawCtx
        if (e.offsetX || e.layerX) {
          let pointX = e.offsetX == undefined ? e.layerX : e.offsetX;
          let pointY = e.offsetY == undefined ? e.layerY : e.offsetY;
          let lastPoint = this.drawingPoints[this.drawingPoints.length-1] || []
          if (lastPoint[0] !== pointX || lastPoint[1] !== pointY) {
            this.drawingPoints.push([pointX, pointY])
          }
          if (this.drawingPoints.length >= 2) {
            this.drawImageDblClickFn()
          }
        }
      },
      drawImageMoveFn(e) {
        let drawCtx = this.drawCtx
        if (e.offsetX || e.layerX) {
          let pointX = e.offsetX == undefined ? e.layerX : e.offsetX;
          let pointY = e.offsetY == undefined ? e.layerY : e.offsetY;
          // 绘制
          drawCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
   
          // 绘制点

          if (!this.drawingPoints[0]) {
            return
          }

          let arr = [this.drawingPoints[0], [this.drawingPoints[0][0], pointY], [pointX, pointY], [pointX, this.drawingPoints[0][1]]]

          // drawCtx.fillStyle = 'blue'
          // this.drawingPoints.forEach((item, i) => {
          //   drawCtx.beginPath();
          //   drawCtx.arc(...item, 6, 0, 180)
          //   drawCtx.fill(); //填充
          // })
   
          // 绘制动态区域
          drawCtx.save()
          drawCtx.beginPath();
          arr.forEach((item, i) => {
            drawCtx.lineTo(...item)
          })
          drawCtx.lineTo(...arr[0])
          drawCtx.lineWidth = "3";
          drawCtx.strokeStyle= "blue";
          drawCtx.fillStyle = 'rgba(255, 0, 0, 0.3)'
          drawCtx.stroke();
          drawCtx.fill(); //填充
          drawCtx.restore()
        }
      },
      drawImageDblClickFn(e) {
        let drawCtx = this.drawCtx

        // 清空绘制图层
        drawCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
        // 绘制区域至保存图层
        this.drawSaveArea(this.drawingPoints)
   
        this.drawedPoints.push(this.drawingPoints)
        this.drawingPoints = []
        this.isDrawing = false
   
        // 绘制结束逻辑
        drawCanvas.removeEventListener("click", this.drawImageClickFn)
        // drawCanvas.removeEventListener("dblclick", this.drawImageDblClickFn)
        drawCanvas.removeEventListener("mousemove", this.drawImageMoveFn)
      },
      drawSaveArea(points) {
        if(!points instanceof Array || points.length === 0) return
        this.saveCtx.save()
        this.saveCtx.beginPath();

        let arr = [points[0], [points[0][0], points[1][1]], points[1], [points[1][0], points[0][1]]]

        arr.forEach((item, i) => {
          this.saveCtx.lineTo(...item)
        })
        this.saveCtx.closePath()
        this.saveCtx.lineWidth="2";
        this.saveCtx.fillStyle = 'rgba(255,0, 255, 0.3)'
        this.saveCtx.strokeStyle= "red";
        this.saveCtx.stroke();
        this.saveCtx.fill(); //填充
        this.saveCtx.restore()
      },
   
      savePoints() { // 将画布坐标数据转换成提交数据
        let objectPoints = []
        // "object": [{"polygon": {"x1":700,"y1":273,"x2":975,"y2":278,"x3":1107,"y3":368,"x4":718,"y4":354} }]
        objectPoints = this.drawedPoints.map(area => {
          return [area[0][0], area[0][1], area[1][0], area[1][1]].toString()
        })
        this.submitData = objectPoints
        console.log('最终提交数据', objectPoints)
      },
      renderDatas() { // 将提交数据数据转换成画布坐标
        this.drawedPoints = this.submitData.map(item => {
          let arr = item.split(',')
          let points = [[arr[0], arr[1]], [arr[2], arr[3]]]
          this.drawSaveArea(points)
          return points
        })
      },
    }
  };
  </script>
  <style lang="scss" scoped>
  .tool-box {
    position: absolute;
    top: 0;
    width: 90vw;
    height: 40px;
    padding: 5px 30px;
    margin: 0 auto 0;
    box-sizing: border-box;
    text-align: right;
    z-index: 999;
  }
  .canvas-wrap {
    // width: 80vw;
    // height: 45vw;
    width: 100vw;
    height: 100vh;
    background-color: #000;//#fff;
    position: relative;
  }
  #imgCanvas, #drawCanvas, #saveCanvas {
    background: rgba(255, 0, 255, 0);
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  #drawCanvas {
    z-index: 2;
  }

//   canvas{
//     width: 100%;
//     height: 100%;
//   }
  </style>